import React from 'react';
import { Tooltip, Button, Popover, Icon } from 'antd';
import { IconApprover, IconPaperPlane, IconOrg, IconFlag } from '@/components/Custom/Icons';
import styles from './index.less';
import { NodeUtils } from './util.js';

const FlowCard = ({ data, verifyMode, onEmits, style, updateTCardTitle, scopeGroup }) => {
    const notEmptyArray = arr => Array.isArray(arr) && arr.length > 0;
    const hasBranch = sdata => notEmptyArray(sdata.conditionNodes);
    const isCondition = sdata => sdata.type === 'condition';
    const stopPro = ev => ev.stopPropagation();
    const { scopeLabel = [] } = scopeGroup;

    /**
     *事件触发器 统筹本组件所有事件并转发到父组件中
     * @param { Object } 包含event（事件名）和args（事件参数）两个参数
     */
    const eventLancher = (e, event, ...args) => {
        e.stopPropagation();
        const param = { event, args };
        if (onEmits) {
            onEmits(param);
        }
    };

    const createNormalCard = conf => {
        const classList = [styles.flowPathCard];
        const afterTrue = (isTrue, name) => isTrue && classList.push(name) && isTrue;
        const isStartNode = afterTrue(NodeUtils.isStartNode(conf), styles.startNode);
        const isApprNode = afterTrue(NodeUtils.isApproverNode(conf), styles.approver);
        const isCopyNode = afterTrue(NodeUtils.isCopyNode(conf), styles.copy);
        return (
            <section
                className={classList.join(' ')}
                onClick={e => {
                    eventLancher(e, 'edit', conf);
                }}
            >
                <header className={styles.header}>
                    <div className={styles.titleBox} style={{ height: '100%', width: 190 }}>
                        {isStartNode && <IconFlag style={{ fontSize: 12, color: 'white', marginRight: 4 }} />}
                        {isApprNode && <IconApprover style={{ fontSize: 12, color: 'white', marginRight: 4 }} />}
                        {isCopyNode && <IconPaperPlane style={{ fontSize: 12, color: 'white', marginRight: 4 }} />}
                        <span className={styles.titleText}>{conf.properties.title}</span>
                        {!isStartNode && (
                            <input
                                value={conf.properties.title}
                                className={styles.titleInput}
                                style={{ marginTop: 3 }}
                                onClick={stopPro}
                                onChange={e => {
                                    updateTCardTitle(conf, e.target.value);
                                }}
                            />
                        )}
                    </div>
                    <div className={styles.actions} style={{ marginRight: 4 }}>
                        <Icon onClick={e => eventLancher(e, 'deleteNode', conf, data)} type="close" />
                    </div>
                </header>
                <div className={styles.body}>
                    <div className={styles.text}>
                        {isStartNode && scopeLabel.length > 0 ? scopeLabel.join('，') : conf.content}
                    </div>
                    <div className={`${styles.iconWrapper} ${styles.right}`}>
                        <Icon type="right" />
                    </div>
                </div>
            </section>
        );
    };
    const nodes = {
        start: sdata => createNormalCard(sdata),
        approver: sdata => createNormalCard(sdata),
        copy: sdata => createNormalCard(sdata),
        condition(conf) {
            return (
                <section
                    className={`${styles.flowPathCard} ${styles.condition}`}
                    onClick={e => {
                        eventLancher(e, 'edit', conf);
                    }}
                >
                    <header className={styles.header}>
                        <div className={styles.titleBox} style={{ height: 200, width: 160 }}>
                            <span className={styles.titleText}>{conf.properties.title}</span>
                            <input
                                value={conf.properties.title}
                                className={styles.titleInput}
                                style={{ marginTop: 1 }}
                                onClick={stopPro}
                                onChange={e => {
                                    updateTCardTitle(conf, e.target.value);
                                }}
                            />
                        </div>
                        <span className={styles.priority}>优先级{conf.properties.priority + 1}</span>
                        <div className={styles.actions}>
                            <Icon onClick={e => eventLancher(e, 'deleteNode', conf, data)} type="close" />
                        </div>
                    </header>
                    <div className={styles.body}>
                        <div
                            className={styles.text}
                            // eslint-disable-next-line react/no-danger
                            dangerouslySetInnerHTML={{ __html: String(conf.content).replace(/\n/g, '<br/>') }}
                        ></div>
                    </div>
                    {conf.properties.isDefault && <span className={styles.defalut}></span>}
                </section>
            );
        }
    };

    const addNodeButton = (sdata, isBranch = false) => (
        // 只有非条件节点和条件分支树下面的那个按钮 才能添加新分支树
        <div className={`${styles.addNodeBtnBox} ${styles.flex} ${styles.justifyCenter}`}>
            <div className={styles.addNodeBtn}>
                <Popover
                    placement="right"
                    trigger="click"
                    overlayStyle={{ width: 266 }}
                    content={
                        <div className={styles.conditionBox}>
                            <div>
                                <div
                                    className={`${styles.conditionIcon} ${styles.btnApproval}`}
                                    onClick={e => {
                                        eventLancher(e, 'addApprovalNode', sdata, isBranch);
                                    }}
                                >
                                    <IconApprover />
                                </div>
                                审批人
                            </div>

                            <div>
                                <div
                                    className={`${styles.conditionIcon} ${styles.btnCopy}`}
                                    onClick={e => {
                                        eventLancher(e, 'addCopyNode', sdata, isBranch);
                                    }}
                                >
                                    <IconPaperPlane />
                                </div>
                                抄送人
                            </div>

                            <div>
                                <div
                                    className={`${styles.conditionIcon} ${styles.btnAppend}`}
                                    onClick={e => {
                                        eventLancher(e, 'appendBranch', sdata, isBranch);
                                    }}
                                >
                                    <IconOrg />
                                </div>
                                条件分支
                            </div>
                        </div>
                    }
                >
                    <Button type="primary" className={styles.reverseBtn} shape="circle" icon="plus" />
                </Popover>
            </div>
        </div>
    );
    const NodeFactory = sdata => {
        if (!sdata) return;
        const showErrorTip = verifyMode && NodeUtils.checkNode(sdata) === false;
        const res = [];
        let branchNode = '';
        let errorTxt = '未设置条件';
        if (NodeUtils.isApproverNode(sdata)) {
            errorTxt = '未选择审批人';
        } else if (NodeUtils.isCopyNode(sdata)) {
            errorTxt = '未选择抄送人';
        }
        const selfNode = (
            <div className={styles.nodeWrap} key={sdata.nodeId}>
                <div className={`${styles.nodeWrapBox} ${styles[sdata.type]} ${showErrorTip ? styles.error : ''}`}>
                    <Tooltip title={errorTxt} placement="top">
                        <div
                            className={styles.errorTip}
                            onClick={e => {
                                eventLancher(e, 'edit', sdata);
                            }}
                        >
                            !
                        </div>
                    </Tooltip>
                    {nodes[sdata.type](sdata)}
                    {addNodeButton(sdata)}
                </div>
            </div>
        );

        if (hasBranch(sdata)) {
            // 如果节点是数组 一定为条件分支 添加分支样式包裹
            branchNode = (
                <div className={styles.branchWrap} key={`${sdata.nodeId}-branch`}>
                    <div className={styles.branchBoxWrap}>
                        <div
                            className={`${styles.branchBox} ${styles.flex} ${styles.justifyCenter} ${styles.relative}`}
                        >
                            <Button
                                className={styles.btn}
                                onClick={e => {
                                    eventLancher(e, 'appendConditionNode', sdata);
                                }}
                            >
                                添加条件
                            </Button>
                            {sdata.conditionNodes.map(d => NodeFactory(d))}
                        </div>
                    </div>
                    {addNodeButton(sdata, true)}
                </div>
            );
        }

        if (isCondition(sdata)) {
            // eslint-disable-next-line consistent-return
            return (
                <div className={styles.colBox} key={`${sdata.nodeId}-condition`}>
                    <div className={styles.centerLine}></div>
                    <div className={styles.topCoverLine}></div>
                    <div className={styles.bottomCoverLine}></div>
                    {selfNode}
                    {branchNode}
                    {NodeFactory(sdata.childNode)}
                </div>
            );
        }

        res.push(selfNode);
        if (branchNode) {
            res.push(branchNode);
        }
        if (sdata.childNode) {
            res.push(NodeFactory(sdata.childNode));
        }
        // eslint-disable-next-line consistent-return
        return res;
    };

    const addEndNode = () => <section className={styles.endNode}>流程结束</section>;

    return (
        <div
            style={{
                display: 'inline-flex',
                flexDirection: 'column',
                alignItems: 'center',
                ...style
            }}
        >
            {data && NodeFactory(data)}
            {addEndNode()}
        </div>
    );
};

export default FlowCard;
